package com.luxk.dbt;

public class ExecBlockPostwork extends ExecBlock {
	
	public ExecBlockPostwork(String name, ExecIF parent, MainContext mCtx) {
		super(name, parent, mCtx);
		this.name = name;
		this.parent = parent;
		this.mCtx = mCtx;
		
		this.result = new Result(this, name);
	}

	@Override
	public ExecIF duplicate(ExecIF parent) throws DBTException {
		throw new DBTException(
				this.getClass().getName() + " unsupport duplicate",
				this.line);
	}

	@Override
	public void prepareInternal() throws DBTException {
		
		if(!this.mCtx.isRunPostwork())
			return;
	}
	
	@Override
	public void runInternal() throws DBTException {
		
		if(!this.mCtx.isRunPostwork())
			return;
		
		this.result.begin();

		try {
			for(ExecIF e: this.children)
				e.run();
		} catch(DBTException ee) {
			this.result.setFail(-1, ee.getMessage());
			throw ee;
		} finally {}
		
		do {
			// wait for 1 sec
			synchronized(this) {
				try {
					wait(1 * 1000);
				} catch(InterruptedException e) {}
			}
		} while(!isFinished());
		
		this.result.setSuccess();
	}
	
	@Override
	public void cleanupInternal() throws DBTException {}
	
	private boolean isFinished() {
		boolean finished = true;
		
		for(ExecIF e: this.children) {
			if(e instanceof ExecBlockThreads &&
					!((ExecBlockThreads)e).isFinished()) {
				finished = false;
			}
			if(e instanceof ExecBlockThread &&
					!((ExecBlockThread)e).isFinished()) {
				finished = false;
			}
		}
		
		return finished;
	}
}
